<template>
  <div class="categories-container">
    <div class="header">
      <h2>商品类别管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon>
          <Plus />
        </el-icon>
        新增类别
      </el-button>
    </div>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="categories" stripe style="width: 100%" :row-key="(row) => row.id">
        <el-table-column prop="id" label="ID" width="autoauto" />
        <el-table-column prop="name" label="类别名称" width="autoauto" />
        <!-- <el-table-column prop="description" label="描述" min-width="300" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="160">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
</el-table-column> -->
        <el-table-column prop="isUse" label="是否启用" width="auto">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.isUse)">
              {{ getStatusText(row.isUse) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="auto" fixed="right">
          <template #default="{ row }">
            <el-button size="small" type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15, 20]"
          :total="total" layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </el-card>
    <!-- 分页 -->

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑类别' : '新增类别'" width="500px"
      :before-close="handleDialogClose">
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="类别名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入类别名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="是否启用" prop="isUse">
          <el-switch v-model="form.isUse" active-text="启用" inactive-text="禁用" />
        </el-form-item>
        <!-- <el-form-item label="描述" prop="description">
          <el-input v-model="form.description" type="textarea" :rows="3" placeholder="请输入类别描述" maxlength="200"
            show-word-limit />
        </el-form-item> -->

      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="submitting">
          {{ isEdit ? '更新' : '创建' }}
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, FormRules } from 'element-plus'
import type { Category as CategoryType } from '@/types'
import request from '@/utils/request'
import axios from 'axios'

// 响应式数据
const loading = ref(false)
const submitting = ref(false)
const categories = ref<CategoryType[]>([])
const dialogVisible = ref(false)
const isEdit = ref(false)
const currentCategory = ref<CategoryType | null>(null)
const formRef = ref<FormInstance>()
const currentPage = ref(1)
const pageSize = ref(5)
const total = ref(0)

// 表单数据
const form = reactive({
  name: '',
  description: '',
  isUse: true
})

// 表单验证规则
const rules: FormRules = {
  name: [
    { required: true, message: '请输入类别名称', trigger: 'blur' },
    { min: 2, max: 50, message: '类别名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 200, message: '描述长度不能超过 200 个字符', trigger: 'blur' }
  ]
}

// 获取类别列表
const loadCategories = async () => {
  loading.value = true
  try {
    const response = await request.get('/category/list', {
      params: {
        pageNum: currentPage.value,
        pageSize: pageSize.value,
      }
    })as any
     console.log(response);
    
    // 确保数据是数组
    const dataArray = Array.isArray(response.data.data) ? response.data.data : []
    categories.value = dataArray
    total.value = response.data.allRow || 0

  } catch (error) {
    ElMessage.error('获取类别列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  loadCategories()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadCategories()
}
// 新增类别
const handleAdd = () => {
  isEdit.value = false
  currentCategory.value = null
  Object.assign(form, {
    name: '',
    // description: '',
    isUse: true
  })
  dialogVisible.value = true
}

// 编辑类别
const handleEdit = (row: CategoryType) => {
  isEdit.value = true
  currentCategory.value = row
  Object.assign(form, {
    name: row.name,
    isUse: row.isUse,
    // description: row.description || ''
  })
  dialogVisible.value = true
}

// 删除类别
const handleDelete = async (row: CategoryType) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除类别"${row.name}"吗？删除后该类别下的商品将无法正常显示。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    request.delete('/category/delete/' + row.id)
    ElMessage.success('删除成功')
    loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
    }
  }
}

// 获取状态类型
const getStatusType = (isUse: boolean) => {
  switch (isUse) {
    case false: return 'warning'
    case true: return 'success'
    default: return 'success'
  }
}

// 获取状态文本
const getStatusText = (isUse: boolean) => {
  switch (isUse) {
    case false: return '未启用'
    case true: return '已启用'
    default: return '已启用'
  }
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitting.value = true

    const categoryData = {
      ...(isEdit.value && currentCategory.value?.id ? { id: currentCategory.value.id } : {}),
      name: form.name,
      isUse: form.isUse
    }
    request.put('/category/edit', categoryData)
    if (isEdit.value) {
      ElMessage.success('更新成功')
    } else {
      ElMessage.success('创建成功')
    }

    dialogVisible.value = false
    loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(isEdit.value ? '更新失败' : '创建失败')
    }
  } finally {
    submitting.value = false
  }
}

// 关闭对话框
const handleDialogClose = () => {
  dialogVisible.value = false
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

// 初始化
onMounted(() => {
  // 确保数据是数组
  if (!Array.isArray(categories.value)) {
    categories.value = []
  }
  loadCategories()
})
</script>

<style scoped lang="scss">
.categories-container {
  padding: 20px;

  .header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      color: $text-color;
    }
  }

  .table-card {
    .el-table {
      .el-button {
        margin-right: 8px;

        &:last-child {
          margin-right: 0;
        }
      }
    }
  }
}
</style>